﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows;
using System.Windows.Media;

namespace DataChangeTools.Behavior
{
    public class ListBoxFocusBehavior
    {

        public static readonly DependencyProperty HandleTabNavigationProperty =
       DependencyProperty.RegisterAttached(
           "HandleTabNavigation",
           typeof(bool),
           typeof(ListBoxFocusBehavior),
           new PropertyMetadata(false, OnHandleTabNavigationChanged)
       );

        public static bool GetHandleTabNavigation(DependencyObject obj) =>
            (bool)obj.GetValue(HandleTabNavigationProperty);

        public static void SetHandleTabNavigation(DependencyObject obj, bool value) =>
            obj.SetValue(HandleTabNavigationProperty, value);

        private static void OnHandleTabNavigationChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is System.Windows.Controls.TextBox textBox && e.NewValue is bool enable && enable)
            {
                textBox.PreviewKeyDown += (sender, args) =>
                {
                    if (args.Key == Key.Tab)
                    {
                        var listBoxItem = FindAncestor<System.Windows.Controls.ListBoxItem>(textBox);
                        if (listBoxItem == null) return;

                        var listBox = ItemsControl.ItemsControlFromItemContainer(listBoxItem) as System.Windows.Controls.ListBox;
                        int currentIndex = listBox.ItemContainerGenerator.IndexFromContainer(listBoxItem);
                        int direction = (args.KeyboardDevice.Modifiers & ModifierKeys.Shift) != 0 ? -1 : 1;
                        int nextIndex = currentIndex + direction;

                        if (nextIndex >= 0 && nextIndex < listBox.Items.Count)
                        {
                            var nextItem = listBox.ItemContainerGenerator.ContainerFromIndex(nextIndex) as ListBoxItem;
                            var nextTextBox = FindVisualChild<System.Windows.Controls.TextBox>(nextItem);
                            nextTextBox?.Focus();
                            args.Handled = true;
                        }
                    }
                };
            }
        }

        // 查找父级容器
        public static T FindAncestor<T>(DependencyObject current) where T : DependencyObject
        {
            do
            {
                if (current is T ancestor)
                    return ancestor;
                current = VisualTreeHelper.GetParent(current);
            } while (current != null);
            return null;
        }

        // 查找子级控件
        public static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                var child = VisualTreeHelper.GetChild(obj, i);
                if (child is T result)
                    return result;
                var childResult = FindVisualChild<T>(child);
                if (childResult != null)
                    return childResult;
            }
            return null;
        }

    }
}
